%To obtain sampled data from SoundCard

%   Copyright 2013
%   Authors:    Salvador Zendejas
%   Project:    Intel Cup 2013
%   Date:       Sept/29th/2013

%
%   Function  that obtain data from the SoundCard of a PC system
%       the sound card really is a ADC, so we can get data capturing such
%       as an audio (WAV). We must sampled and quantized and cast to a data
%       values.
%   --Parameters:
%			time = The record time (in seconds)
%           Fs = Sampling Freq
%           bits = amount of bits to quantize the ADC
%           Ch = Number of Channels to get the data
%           Id = Id of the soundcard 


% data = f_get_dataSoundCard(time, Fs, bits, Ch, Id)
%Examples:
% data = f_get_dataSoundCard(2, 8e3, 16, 1, 0); %2 seconds sampling at 8kHz
%                               16 bits, 1 channel and Id=0

function[data] = f_get_dataSoundCard(time, Fs, bits, Ch, Id)

%f_get_dataSoundCard Returns a vector where the data are provided from 
%capturing a signal introduced through the ADC embedded on the SoundCard
% (Lin In or Mic)

if( nargin == 0 )
		disp( 'At least one argument is needed' );
        time = 0.1;
end

if( nargin <= 4 )
    sndcard_info = audiodevinfo(); %#obtener datos para identificar el ID
    Name_dev = sndcard_info.input(1,1).Name;
    Id = sndcard_info.input(1,1).ID;
    str = sprintf( 'Id default: %d, which is %s', Id, Name_dev);
    disp(str);
end

if( nargin <= 3 || Ch == 0 )
    disp( 'Using one channels input');
    Ch = 1;
end

if( nargin <= 2 || bits == 0 )
    disp( 'Using 16 bits to quantize the ADC values');
    bits = 16;
end

if( nargin <= 1 || Fs == 0 )
    disp( 'Using a 44100Hz sampled freq');
    Fs = 44100;
end

%Fs = 44100; bits = 16; ch=1; Id=0;
%time = 2; %seconds
recObj = audiorecorder(Fs, bits, Ch, Id);
disp('Start recording');
recordblocking(recObj,time);
disp('Stop recording')
play(recObj);
data = getaudiodata(recObj);

end %__end__ function